package edu.security;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class MySecurityFilter implements Filter {
	
	protected FilterConfig fConfig;
	protected String ignoreURL = null;
	protected String redirectURL = null;
	protected List<String> allIgnoreURL = new ArrayList<String>();
	
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request =(HttpServletRequest)servletRequest;   
		HttpServletResponse response =(HttpServletResponse)servletResponse;   
		
		String url = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/"));

//		System.out.println(url);
		
		if(urlCheck(url)== false) {
			HttpSession session = request.getSession();
//			System.out.println("do filter " + session.getAttribute("loginUser"));
			
			if(session.getAttribute("loginUser") == null)
				response.sendRedirect(request.getContextPath()+ redirectURL);
			
		}
		
		chain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
		this.fConfig= fConfig;
		
		redirectURL = fConfig.getInitParameter("redirectURL");
		if(!redirectURL.startsWith("/")) {
			redirectURL = redirectURL + "/";
		}
		
		ignoreURL = fConfig.getInitParameter("ignoreURL");
		
		StringTokenizer tokenizer = new StringTokenizer(ignoreURL, ",");
		while (tokenizer.hasMoreElements()) {
			allIgnoreURL.add(tokenizer.nextElement().toString());
		}
		System.out.println("filter start");
	}
	
	private boolean urlCheck(String url) {
		int size = allIgnoreURL.size();
		for(int i = 0; i < size; i++) {
			if(allIgnoreURL.get(i).equals(url))
				return true;
		}
		return false;
	}
}